package com.apiinvoke.controller;

import com.apiinvoke.CommonData;
import com.apiinvoke.config.ApiCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@RestController
public class ApiController {

    @Autowired
    private ApiCache apiCache;

    @RequestMapping("/api")
    public Object api(CommonData commonData) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        final Method method = apiCache.getMethod(commonData.getMode());

        if (method == null) {
            return "not found the interface";
        }
        Object o = method.getDeclaringClass().getDeclaredConstructor().newInstance();
        return ReflectionUtils.invokeMethod(method, o, commonData);
    }
}
